import binascii
import re

# 匹配模式有4种，字符串、字符串正则、16进制、16进制正则。
MODE_STRING = 0
MODE_STRING_REGEX = 1
MODE_HEX = 2
MODE_HEX_REGEX = 3

class Data(object):
    def __init__(self):
        self._type = "any"
        self._mime = "any"

    def from_path(self, path):
        self._path = path
        with open(path, "rb") as f:
            self.from_bytes(f.read())

    def from_io(self, _io):
        self.from_bytes(_io.read())

    def from_bytes(self, _bytes):
        self._text = _bytes.decode("utf-8", errors="ignore")
        self._hex = binascii.hexlify(_bytes).decode("ascii")

    def type(self):
        return self._type
    
    def mime(self):
        return self._mime

    def get_path(self):
        return self._path

    def set_path(self, value):
        self._path = value
    

    def match(self, s, flag):
        if flag == MODE_STRING:
            return s in self._text
        
        if flag == MODE_STRING_REGEX:
            return re.search(s, self._text) is not None
        
        if flag == MODE_HEX:
            return s in self._hex

        return re.search(s, self._hex) is not None

    def get_sub_files(self):
        """获取子文件

        :return: [description]
        :rtype: [bytes]
        """
        return self._sub_files
    
    def close(self):
        pass
